package com.hsgene.security.service.impl;

import com.google.common.base.Preconditions;
import com.hsgene.common.util.basic.Base64Utils;
import com.hsgene.common.util.security.RSAUtils;
import com.hsgene.security.service.RSASecurityService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * RSASecurityServiceImpl
 *
 * @author wangbing
 * @version 1.0, 2018/7/11
 */
@Service
public class RSASecurityServiceImpl implements RSASecurityService {

    private static final Logger logger = LogManager.getLogger(RSASecurityServiceImpl.class);

    @Value("${rsa.private.key}")
    private String privateKey;

    @Value("${rsa.public.key}")
    private String publicKey;

    /**
     * 解密数据
     *
     * @param dataStr 加密的数据字符串
     * @return 解密后的数据字符串
     */
    @Override
    public String decryptData(String dataStr) {
        Preconditions.checkArgument(StringUtils.isNotBlank(dataStr), "要解密的数据字符串不能为空！");

        try {
            byte[] decryptedData = RSAUtils.decryptByPrivateKey(Base64Utils.decryptBASE64(dataStr), privateKey);
            return new String(decryptedData, "UTF-8");
        } catch (Exception e) {
            logger.error("解密发生异常！，dataStr={}", dataStr, e);
            throw new IllegalStateException("解密发生异常！");
        }
    }

    /**
     * 加密数据
     *
     * @param dataStr 原数据字符串
     * @return 加密后的数据字符串
     */
    @Override
    public String encryptData(String dataStr) {
        Preconditions.checkArgument(StringUtils.isNotBlank(dataStr), "要加密的数据字符串不能为空！");
        try {
            return Base64Utils.encryptBASE64(RSAUtils.encryptByPublicKey(dataStr.getBytes(), publicKey));
        } catch (Exception e) {
            logger.error("加密发生异常！，dataStr={}", dataStr, e);
            throw new IllegalStateException("加密发生异常！");
        }
    }
}
